<template>
    
    <el-dialog title="耗材入库" :visible.sync="parentShow" width="1000px" >
        <!-- 选择仓库和写入备注 -->
        <el-form label-width="80px" size="small" @submit.native.prevent>
            <el-form-item label="选择仓库">
                <el-select placeholder="请选择" v-model="warehouse_id" value-key="warehouse_id">
                    <el-option v-for="option in options" :key="option.warehouse_id" :value="option.warehouse_id"  :label="option.warehouse_name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注说明">
                <el-input v-model="remark"></el-input>
            </el-form-item>
        </el-form>
        <!-- 选择耗材和删除耗材按钮 -->
        <el-row class="mb-20">
            <el-button onFocus="this.blur()" mini @click="getMeterialsList('openDailog')">选择耗材</el-button>
            <el-button :type="selIds.length===0?'info':'danger'" mini onFocus="this.blur()" :disabled="selIds.length===0" @click="removeMeterial">删除选中</el-button>
        </el-row>
        <!-- 已选耗材列表 -->
        <el-table 
            :data="tableData" 
            max-height="250" 
            @selection-change="val=>selIds=val.map(item=>{ return item.consumable_item_id })" 
            style="width: 100%;"
            tooltip-effect="dark"  
            :header-cell-style="{'background-color':'#EEF1F6','height':'45px'}">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column v-for="item in tableHead.filter((d,i)=>{if(i<3){return d}})" :key="item.prop" :label="item.label" :prop="item.prop" align="left"></el-table-column>
            <el-table-column label="单价" prop="univalence" align="center" width="180">
                <template slot-scope="scope">
                    <el-form :ref="'f'+scope.row.consumable_item_id" :model="tableData[scope.$index]" @submit.native.prevent>
                        <el-form-item :prop="scope.column.property" :rules="rule.price">
                            <el-input v-model="tableData[scope.$index][scope.column.property]"></el-input>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="数量" prop="count" align="center" width="180">
                <template slot-scope="scope">
                    <el-form :ref="'n'+scope.row.consumable_item_id" :model="tableData[scope.$index]" @submit.native.prevent>
                        <el-form-item :prop="scope.column.property" :rules="rule.number">
                            <el-input v-model.number="tableData[scope.$index][scope.column.property]"></el-input>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
        </el-table>
        <!-- 耗材入库弹窗底部按钮 -->
        
        <div slot="footer" class="dialog-footer">
            <button class="el-button" style="margin-right:20px" onFocus="this.blur()" @click="parentShow = false"><span>取消</span></button>
            <button class="el-button el-button--primary" type="primary" onFocus="this.blur()" style="margin-right:40px" @click="submitToStore"><span>确定</span></button>
        </div>


        
         <!-- 选择耗材 -->
        <dialog-vue dialogTitle="选择耗材" dawidth="width" :dialogVisible="childShow" @dialogVisibleChangeFn="dialogVisibleChangeFn">
            <boxMessage-vue ref="ruleForm" :ruleForm="{formList: []}" :rules="{}" @goCancel="goBackFn" @goSubmit="goSubmit" :inline="true">
                <el-input placeholder="请输入内容" v-model="pageSmallQuery.message" prefix-icon="el-icon-search" class="mb-20 search-inp">
                    <el-button slot="append" icon="el-icon-search" @click="getMeterialsList"></el-button>
                </el-input>
                <lpj-table-vue ref="lpjTable2" rowKey='consumable_item_id' :tableData="childTableData" :tableHeaderData="tableHead"   @handleSelectionChange="handleSelectionChange"  ></lpj-table-vue>
                <pagination v-if="paginationMes&&paginationMes.total>10" align="right" :paginationMes="paginationMes" @sizeChangeFn="sizeChangeFn" @currentChangeFn="currentChangeFn"></pagination> 
            </boxMessage-vue>
        </dialog-vue>

    </el-dialog>
</template>

<script>
 /* eslint-disable */ 
import { getConsumables, consumablesStorage } from '../api'
import { getAllWarehouses} from '@/api'
// import BoxMessageVue from "@/components/LpjBoxMessageVue"
// import DialogVue from "@/components/LpjDialogVue"
import Pagination from "@/components/Pagination"
import LpjTableVue from "@/components/LpjTableVue"

export default {
    name:'InWarehouse',
    components:{Pagination,LpjTableVue},
    data(){
        /** 非0的正整数 */
        var notZeroOrInteger = (rule, value, callback) => {
            let reg  = /^[0-9]*[1-9][0-9]*$/;
            !reg.test(value) ? callback(new Error('请输入大于0的正整数')):callback()
        }
        /** 非0的正数 */
        var notZeroOrPlusNumber = (rule, value, callback) => {
            let reg = /^([0-9]\d*)(\.{0,1}\d*[0-9])?$/
            value === 0 || value === "0" || !reg.test(value) ? callback(new Error('请输入大于0的正数')) : callback()
        }
        return {
            /** 表头 俩个表格的 */
            tableHead:[
                {hasCheckBox:true, /**表格是否有选择CheckBox */
                 saveSelection:true, /**数据更新是否保存之前选择 */
                },
                {label:"耗材编码",prop:"consumable_item_no",},
                {label:"耗材名称",prop:"consumable_item_name"},
                {label:"耗材分类",prop:"cate_name"},
                {label:"品牌",prop:"brand"},
                {label:"规格型号",prop:"model"},
                {label:"单位",prop:"unit"},
            ],
            paginationMes:{},
            /** 耗材列表 */
            childTableData:[],
            /** 选中的耗材列表 */
            tableData:[],
            /** 父级弹窗显示 */
            parentShow:false,
            /** 子弹窗的显示 */
            childShow:false,
            /** 仓库列表 */
            options:[],
            /** 分页请求耗材列参数 */
            pageSmallQuery:{
                searchKey:'',//搜索内容
                pageSize:5,
                page:1
            },
            /** 数据大小 */
            childTotal:0,
            /** 输入单价和数量的耗材的ids */
            selIds:[],
            /** 表单校验规则 */
            rule:{
                price:[{required: true, validator:notZeroOrPlusNumber,trigger: "blur"}],
                number:[{required: true, validator:notZeroOrInteger,trigger: "blur"}],
            },
            /** 选中的仓库 */
            warehouse_id:'',
            /**备注 */
            remark:'',
            /** 选中的耗材列表 */
            selMeterial:[],
        }
    },
    created(){
        /** 获取仓库列表 */ 
        getAllWarehouses().then(res=> this.options = res)
    },
    methods:{
        /** 提交 */
        submitToStore(){
            let formValidator = true
            if(!this.warehouse_id) return this.$message.warning('请选择仓库')
            let consumable_data = this.tableData.map(item=>{
                /** 校验 */
                this.$refs['f'+item.consumable_item_id].validate(valid => valid ? null : formValidator = valid)
                this.$refs['n'+item.consumable_item_id].validate(valid => valid ? null : formValidator = valid)
                /** 如果univalence是字符串，小数则转成float非小数转int,方便计算 */
                if(typeof item.univalence === 'string'){
                   item.univalence = item.univalence.includes('.') ? parseFloat(item.univalence) : parseInt(item.univalence)
                }
                /** 存入当前耗材信息 */
                return {
                    count:item.count,
                    price:item.univalence,
                    consumable_item_id:item.consumable_item_id,
                }
            })
            if(!formValidator) return false
            /** 提交数据 */
            consumablesStorage({consumable_data,warehouse_id:this.warehouse_id,remark:this.remark}).then(res=>{
                this.$message.success(res)
                this.parentShow = false
                this.$emit('reload')
            })
        },

        /**表格CheckBox勾选事件 */
        handleSelectionChange(selection){
            var arr=selection.map(item=>{
              return{...item,count:0,univalence:0}
            })
            this.selMeterial=arr
        },
        /** 移除选中耗材 */
        removeMeterial(){
            this.tableData = this.tableData.filter(item=>{
                if(!this.selIds.includes(item.consumable_item_id)) return item
            })
            
        },
        /** 获取可入库耗材 */
        getMeterialsList(type){
            getConsumables(this.pageSmallQuery).then(res => {
                this.paginationMes={current_page:Number(res.current_page),total:res.total}
                this.childTableData = res.data
                this.childShow = true
            })
        },
        /*分页当前页 */
        currentChangeFn(val){
            this.pageSmallQuery.page=val
            this.getMeterialsList()
        },
        /*分页每页的条数 */
        sizeChangeFn(val){
            this.pageSmallQuery.pageSize=val
            this.getMeterialsList()
        },
        //点击透明层关闭
        dialogVisibleChangeFn(val){
            this.childShow=val
        },
        //返回页面
        goBackFn(){
            this.childShow=false
        },
        //选择耗材
        goSubmit(){
            this.childShow = false
            this.tableData = this.selMeterial

        },
    },
    watch:{
        parentShow(val){
            if(val){
                /** 初始化参数 */
                this.tableData = []
                this.pageSmallQuery.page = 1
                this.childTotal = 0
                this.selIds = []
                this.warehouse_id = ``
                this.remark = ''
            }
        },
    }
}
</script>

<style lang="stylus" scoped>
.mb-20
    margin-bottom 20px
.search-inp
    >>>.el-input-group__append
        background-color #409eff
        color #ffffff
        border-color #409eff
.dialog-footer
    text-align: center;
    button 
        padding: 9px 15px;
</style>